import csv
import json
import os
import random
import tkinter as tk
from tkinter import filedialog, messagebox

def csv_to_jsonl(csv_file_path, sample_size):
    """将 CSV 文件随机选取 sample_size 行转换为 JSONL 文件"""
    with open(csv_file_path, mode='r', encoding='utf-8') as csv_file:
        csv_reader = list(csv.DictReader(csv_file))

    total_rows = len(csv_reader)
    if total_rows == 0:
        messagebox.showerror("错误", "CSV 文件为空！")
        return

    # 如果 CSV 行数小于用户输入的数量，则转换所有数据
    sample_size = min(sample_size, total_rows)
    selected_data = random.sample(csv_reader, sample_size) if sample_size < total_rows else csv_reader

    jsonl_file_path = f"{os.path.splitext(csv_file_path)[0]}_{sample_size}.jsonl"

    with open(jsonl_file_path, mode='w', encoding='utf-8') as jsonl_file:
        for row in selected_data:
            jsonl_file.write(json.dumps(row, ensure_ascii=False) + '\n')

    messagebox.showinfo("转换成功", f"已转换 {sample_size} 条数据。\n文件名: {jsonl_file_path}")

def select_file():
    """打开文件选择对话框"""
    file_path = filedialog.askopenfilename(filetypes=[("CSV 文件", "*.csv")])
    if file_path:
        try:
            sample_size = int(entry.get())
            if sample_size <= 0:
                raise ValueError
            csv_to_jsonl(file_path, sample_size)
        except ValueError:
            messagebox.showerror("错误", "请输入一个有效的正整数")

# 创建 GUI
root = tk.Tk()
root.title("CSV 转 JSONL 工具")
root.geometry("350x200")

label = tk.Label(root, text="选择 CSV 文件并输入要转换的行数", padx=10, pady=10)
label.pack()

entry = tk.Entry(root)
entry.pack()
entry.insert(0, "10")  # 默认转换 10 行

btn_select = tk.Button(root, text="选择文件", command=select_file)
btn_select.pack()

root.mainloop()
